<template>
  <div class="add-container">
    <div class="add-top">
      <el-page-header @back="goBack" :content="gobacktitle"></el-page-header>
    </div>
    <div class="add-main">
      <div class="add-main-top">
        <div class="add-main-tital">
          <p>调拨单</p>
        </div>
        <div>
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-position="left"
            label-width="0.8rem"
            class="demo-ruleForm"
          >
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="调拨单号">
                  <el-input
                    v-model="ruleForm.pingzhengh"
                    placeholder="请选择"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="物资区分">
                  <el-select
                    v-model="ruleForm.wuziqfid"
                    @change="dataUpdate"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in $util.getWzqf()"
                      :key="index"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="物资分类">
                  <el-select
                    v-model="ruleForm.wuzizyid"
                    @change="dataUpdate"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in Wzzylist"
                      :key="index"
                      :label="item.zhuanyemc"
                      :value="item.zhuanyeid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="主管单位" prop="zhuguandwid">
                  <el-select
                    v-model="ruleForm.zhuguandwid"
                    @change="dataUpdate"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in Zgdwlist"
                      :key="index"
                      :label="item.danweimc"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="发货单位">
                  <el-select
                    v-model="ruleForm.fahuodw"
                    filterable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in sfdwlist"
                      :key="index"
                      :label="item.fawudw"
                      :value="item.fawudw"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="接收单位">
                  <el-select
                    v-model="ruleForm.jieshoudw"
                    filterable
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) in sfdwlist"
                      :key="index"
                      :label="item.fawudw"
                      :value="item.fawudw"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="6">
                <el-form-item label="保障时效">
                  <el-date-picker v-model="ruleForm.baozhangsx" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col> -->

              <el-col :span="6">
                <el-form-item label="调拨依据">
                  <el-input v-model="ruleForm.diaoboyj"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="经办人">
                  <el-input v-model="ruleForm.jingbanr"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="备注">
                  <el-input
                    type="textarea"
                    rows="1"
                    v-model="ruleForm.beizhu"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="add-main-list">
        <div class="list-button-group">
          <div class="button-item">
            <!-- @click="insertEvent()" -->
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="DialogOpenWuzi([])"
            >
              新增
            </el-button>
          </div>
          <div class="button-item">
            <el-button type="danger" icon="el-icon-delete" @click="delwzDetail">
              删除
            </el-button>
          </div>
          <div class="button-item">
            <el-button
              type="primary"
              icon="el-icon-s-check"
              @click="importShow = true"
            >
              导入入库单明细
            </el-button>
          </div>
          <div class="button-item">
            <el-button
              type="primary"
              icon="el-icon-s-check"
              @click="downloadHandle"
            >
              下载模板
            </el-button>
          </div>
        </div>
        <div class="table-list" id="table-list">
          <ux-grid
            border
            show-overflow
            ref="plxTable"
            keep-source
            :height="tabheight"
            :highlightCurrentRow="false"
            widthResize
            :rules="ruleslist"
            @selection-change="selectChange"
            :edit-config="{ trigger: 'click', mode: 'row' }"
          >
            <ux-table-column type="checkbox" width="50" />
            <ux-table-column
              type="index"
              title="序号"
              width="50"
            ></ux-table-column>
            <!-- <ux-table-column field="wuzibm" title="物资代码"></ux-table-column> -->
            <ux-table-column field="wuzimc" title="物资名称"></ux-table-column>
            <ux-table-column field="guigexh" title="规格型号"></ux-table-column>
            <ux-table-column
              field="wuzisl"
              title="数量"
              :edit-render="{ autofocus: '.el-input__inner' }"
            >
              <template v-slot:edit="scope">
                <el-input
                  v-model.trim="scope.row.wuzisl"
                  type="number"
                  :min="1"
                  placeholder="请输入库存数量"
                  @keyup.native="scope.row.wuzisl = oninput(scope.row.wuzisl)"
                />
              </template>
            </ux-table-column>
            <ux-table-column
              show-overflow-tooltip
              field="cankaojg"
              title="单价(元)"
              :edit-render="{ autofocus: '.el-input__inner' }"
            >
              <template v-slot:edit="scope">
                <el-input
                  v-model.trim="scope.row.cankaojg"
                  type="number"
                  placeholder="请输入单价"
                />
              </template>
            </ux-table-column>
            <ux-table-column
              field="picih"
              title="批次号"
              :edit-render="{ autofocus: '.el-input__inner' }"
            >
              <template v-slot:edit="scope">
                <el-input
                  v-model.trim="scope.row.picih"
                  placeholder="请输入批次号"
                />
              </template>
            </ux-table-column>
            <ux-table-column
              show-overflow-tooltip
              field="shengchancj"
              title="生产厂家"
              :edit-render="{ autofocus: '.el-input__inner' }"
            >
              <template v-slot:edit="scope">
                <el-input
                  v-model.trim="scope.row.shengchancj"
                  placeholder="请输入生产厂家"
                />
              </template>
            </ux-table-column>
            <ux-table-column
              show-overflow-tooltip
              field="shengchanrq"
              title="生产日期"
              :edit-render="{ autofocus: '.el-input__inner' }"
            >
              <template v-slot:edit="scope">
                <el-date-picker
                  v-model="scope.row.shengchanrq"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </template>
            </ux-table-column>
            <!-- <ux-table-column show-overflow-tooltip field="baozhiq" title="保质期(月)">
            </ux-table-column> -->
            <!-- <ux-table-column field="wuzisl" title="实际入库数量" :edit-render="{ autofocus: '.el-input__inner' }">
              <template v-slot:edit="scope">
                <el-input v-model.trim="scope.row.wuzisl" type="number" :min="1" placeholder="请输入库存数量"
                  @keyup.native="scope.row.wuzisl = oninput(scope.row.wuzisl)" />
              </template>
            </ux-table-column> -->
          </ux-grid>
          <div class="submit-button">
            <el-button
              type="primary"
              icon="el-icon-circle-check"
              @click="submitForm('ruleForm')"
            >
              确认
            </el-button>
            <el-button type="info" icon="el-icon-delete" @click="goBack">
              取消
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!--新增 物资 -->
    <page-1-add-wuzi
      ref="wuzi-dialog"
      @fetch-data="fetchData"
    ></page-1-add-wuzi>
    <!-- 导入文件start -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="importShow"
      destroy-on-close
      title="导入文件"
      class="m-dialog"
      :append-to-body="true"
    >
      <upload-wz api-url="/rukudbd/importRukudbd" @success="uploadSuccess" />
    </el-dialog>
  </div>
</template>
<script>
  import UploadWz from './uploadWz.vue'
  import { save, queryKufangList, queryPage } from '@/api/warehousing'
  import page1AddWuzi from './page1AddWuzi.vue'
  import { queryFWList } from '@/api/fawudw'
  export default {
    name: 'Page1Add',
    components: { UploadWz, page1AddWuzi },
    props: {
      gobacktitle: {
        type: String,
        default: '新增',
        required: true,
      },
      datarow: {
        type: Object,
        default: function () {
          return {}
        },
      },
    },
    data() {
      return {
        show: true,
        insertData: {},
        ruleForm: {
          datalist: [],
        },
        rules: {
          rukudh: [
            { required: true, message: '请输入入库单号', trigger: 'blur' },
          ],
          kufangid: [
            { required: true, message: '请选择库房', trigger: 'blur' },
          ],
        },
        ruleslist: {
          wuzimc: [
            { required: true, message: '请输入物资名称', trigger: 'blur' },
          ],
          wuzisl: [{ required: true, message: '请输入数量', trigger: 'blur' }],
          chubeidj: [
            { required: true, message: '请输入储备等级', trigger: 'blur' },
          ],
          danjia: [{ required: true, message: '请输入单价', trigger: 'blur' }],
        },
        tabheight: 500,
        importShow: false,
        KufangList: [],
        cbdjList: [],
        Wzzylist: [],
        Zgdwlist: [],
        sfdwlist: [],
      }
    },
    async created() {
      let { data } = await queryFWList({})
      let list = await queryPage({ startTime: this.$util.changeBZTime() })
      this.sfdwlist = data
      this.ruleForm.pingzhengh = this.$util.addPreZero(list.data.total, 'RK')
      //库房
      const kfData = await queryKufangList()
      this.KufangList = kfData.data
      this.Zgdwlist = await this.$util.getZgdw()
      //等级
      this.cbdjList = await this.$util.getZBDJlist()

      //物资分类
      this.Wzzylist = await this.$util.getWzzy()
      let wzqflist = this.$util.getWzqf()
      if (this.gobacktitle == '新增') {
        this.ruleForm.kufangid = this.KufangList[0].id
        this.ruleForm.zhuguandwid = this.Zgdwlist[0].id
        this.ruleForm.wuziqfid = wzqflist[1].id
        this.ruleForm.wuzizyid = this.Wzzylist[0].zhuanyeid
      }
    },
    mounted() {
      // this.getKufangList();

      let height = document.getElementById('table-list').offsetHeight
      this.tabheight = height - 120
      this.ruleForm = Object.assign({}, this.datarow)
      this.$nextTick(() => {
        this.$refs.plxTable.reloadData(this.ruleForm.rukudbdmxList)
      })
    },
    methods: {
      dataUpdate() {
        this.$forceUpdate()
      },
      //下载模板
      downloadHandle() {
        let xhr = new XMLHttpRequest()
        //get后边是public文件夹下需要下载的模板的文件名
        xhr.open('get', `/static/入库单导入明细模板.xlsx`, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
          if (this.status == 200) {
            const downloadElement = document.createElement('a')
            const href = window.URL.createObjectURL(this.response)
            downloadElement.href = href
            //这个也是文件名
            downloadElement.download = '入库单导入明细模板.xlsx'
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href)
          }
        }
        xhr.send()
      },
      goBack() {
        this.$parent.addshow = false
      },

      DialogOpenWuzi(row) {
        this.$refs['wuzi-dialog'].wuzizyid = this.ruleForm.wuzizyid
        this.$refs['wuzi-dialog'].getData()
        this.$refs['wuzi-dialog'].showEdit(row)
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let rukudbdmxList = this.$refs.plxTable.getTableData().fullData
            let arr = []
            if (rukudbdmxList.length != 0) {
              rukudbdmxList.forEach((element) => {
                arr.push({
                  cankaojg: element.cankaojg,
                  guigexh: element.guigexh,
                  // "id": element.id,
                  jiliangdw: element.jiliangdw,
                  picih: element.picih,
                  rukudbdid: element.rukudbdid,
                  shengchancj: element.shengchancj,
                  shengchanrq: element.shengchanrq,
                  baozhiq: element.baozhiq,
                  wuzibm: element.wuzibm,
                  wuziid: element.wuziid,
                  wuzimc: element.wuzimc,
                  wuzisl: element.wuzisl,
                })
              })
            }
            this.ruleForm.rukudbdmxList = arr
            //  this.ruleForm.cangkuid = 'C9886D8A1BBF4DE9B5ACC808FAD498AF'
            // this.ruleForm.id = 'E73AE6A0FB2B40D48195F7FD912AA133'
            const mxLen = this.$refs.plxTable.getTableData().fullData
            if (mxLen.length == 0) {
              this.$message({
                message: '请添加明细',
                type: 'warning',
              })
              return
            }
            this.$refs.plxTable.validate(true).then(async (data) => {
              if (data) {
                // 有错误
              } else {
                const msg = await save(this.ruleForm)
                this.$message({
                  message: msg.msg,
                  type: 'success',
                })
                if (this.gobacktitle == '新增') {
                  this.resetForm() //重置表单
                }
                this.$parent.resetlist()
              }
            })
          } else {
            return false
          }
        })
      },

      resetForm(formName) {
        this.ruleForm = Object.assign({ rukudbdmxList: [] }, [])
        this.$nextTick(() => {
          this.$refs.plxTable.reloadData([])
        })
        // this.$refs[formName].resetFields()
      },
      selectChange(e) {},
      // 添加插入行
      async insertEvent(row) {
        // let record = Object.assign({}, this.insertData[0])
        let record = this.insertData
        // 加入行, 表示加入行的row对象，row为空则插入第一行，为-1插入最后一行
        let { row: newRow } = await this.$refs.plxTable.insertRow(record)
        // 激活单元格编辑
        await this.$refs.plxTable.setActiveRow(newRow)
      },
      delwzDetail() {
        this.$refs.plxTable.remove(this.$refs.plxTable.getCheckboxRecords())
      },
      uploadSuccess(res) {
        this.ruleForm.rukudbdmxList = res.rukudbdmxDto
        this.importShow = false
        this.$nextTick(() => {
          this.$refs.plxTable.reloadData(this.ruleForm.rukudbdmxList)
        })
      },
      oninput(num) {
        return num.replace(/\D/g, '')
      },
      async getKufangList() {
        //库房
        const kfData = await queryKufangList()
        this.KufangList = kfData.data
        this.Zgdwlist = await this.$util.getZgdw()
        //等级
        this.cbdjList = await this.$util.getZBDJlist()

        //物资分类
        this.Wzzylist = await this.$util.getWzzy()
      },
      fetchData(data) {
        this.insertData = data
        //this.insertData[0].wuziid = this.insertData[0].id
        this.insertData.forEach((item) => {
          item.wuziid = item.id
        })
        this.insertEvent()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .add-container {
    position: fixed;
    left: 0;
    top: 0.75rem;
    width: 100%;
    height: 100%;
    z-index: 1000;
    background-color: #f6f8f9;
    padding: 0 0.2rem 1rem 0.2rem;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .add-top {
      padding: 0.1rem 0;

      ::v-deep .el-page-header__title {
        font-size: 0.16rem !important;
      }
    }

    .add-main {
      flex: 1;
      font-weight: bold;
      display: flex;
      flex-direction: column;
      overflow: auto;

      .add-main-top {
        padding: 0.2rem;
        background: #fff;
        border-radius: 0.05rem;

        .add-main-tital {
          font-size: 0.18rem;
          border-left: 0.1rem solid rgb(121, 189, 255);
          padding-left: 0.1rem;

          p {
            margin: 0;
          }
        }

        .search-gropu-item {
          margin-top: 0.2rem;
          width: 90%;
          display: flex;
          // label {
          //   white-space: nowrap;
          //   line-height: 32px;
          //   margin-right: 10px;
          // }
        }

        .el-select {
          width: 100%;
        }
      }

      .add-main-list {
        flex: 1;
        margin-top: 20px;
        background: #fff;
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .list-button-group {
          display: flex;
          flex-direction: row;
          padding-bottom: 20px;

          .button-item {
            padding: 0px 10px;
          }

          .button-item:first-child,
          &:last-child {
            padding: 0px 10px 0 0;
          }
        }

        .table-list {
          flex: 1;
        }
      }

      .el-button {
        font-size: 0.14rem !important;
      }

      ::v-deep {
        .elx-table--header-wrapper {
          background-color: rgb(233, 243, 255);
        }

        .elx-table {
          font-size: 0.14rem !important;
        }

        .elx-body--column {
          height: 0.48rem !important;
          line-height: 0.24rem;
        }

        .elx-header--column {
          background-image: none !important;
          height: 0.48rem !important;
        }

        .el-date-editor.el-input,
        .el-date-editor.el-input--inner {
          width: 100% !important;
        }

        .el-form-item--small.el-form-item {
          margin-bottom: 0px;
          margin-top: 18px;
        }
      }

      .submit-button {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }
</style>
